package com.steward.server.card.impl;

import com.steward.commons.ConstData;
import com.steward.commons.Result;
import com.steward.dao.card.CardMapper;
import com.steward.dao.card.CardServicesRelaMapper;
import com.steward.dao.card.CardTypeServiceMapper;
import com.steward.dao.consume.ConsumeDetailMapper;
import com.steward.dao.consume.ConsumeMapper;
import com.steward.dao.customer.CustomerMapper;
import com.steward.dao.mob.MobGiftActiveMapper;
import com.steward.dao.mob.MobRegMapper;
import com.steward.dao.product.ProductInfoMapper;
import com.steward.exceptions.StewardException;
import com.steward.model.card.Card;
import com.steward.model.card.CardServicesRela;
import com.steward.model.card.CardTypeService;
import com.steward.model.consume.Consume;
import com.steward.model.consume.ConsumeDetail;
import com.steward.model.customer.Customer;
import com.steward.model.mob.MobGiftActive;
import com.steward.model.mob.MobReg;
import com.steward.model.product.ProductInfo;
import com.steward.server.card.CardActiveService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class CardActiveServiceImpl implements CardActiveService {

	private static Logger logger = Logger.getLogger(CardActiveServiceImpl.class);
	@Resource
	private CustomerMapper customerMapper;
	@Resource
	private CardMapper cardMapper;
	@Resource
	private MobRegMapper mobRegMapper;
	@Resource
	private MobGiftActiveMapper mobGiftActiveMapper;
	@Resource
	private CardTypeServiceMapper cardTypeServiceMapper;
	@Resource
	private ProductInfoMapper productInfoMapper;
	@Resource
	private ConsumeMapper consumeMapper;
	@Resource
	private ConsumeDetailMapper consumeDetailMapper;
	@Resource
	private CardServicesRelaMapper cardServicesRelaMapper;

	@Override
	@Transactional
	public Result<String> activeCard(String cardNO, String activeId, String telephone) {
		logger.debug("cardNo:{" + cardNO + "},activeId:{" + activeId + "},telephone:{" + telephone + "}");
		Result<String> result = new Result<String>();
		try {
			Card card = cardMapper.queryCardInfoBycardNo(cardNO);
			//查询时候没有年卡记录
			if (card == null) {
				result.setCode(ConstData.NOT_FOUND_CODE);
				throw new StewardException("0x000A04","没有查询到对应的年卡数据");
			}
			String cardId = card.getId();
			MobGiftActive giftActive = mobGiftActiveMapper.queryGiftActiveInfoWithCardId(cardNO);
			//如果对应的gift为空
			if (giftActive == null) {
				result.setCode(ConstData.NOT_FOUND_CODE);
				throw new StewardException("0x000A04","系统没有对应的激活信息");
			}
			//如果卡被激活过
			if (ConstData.CARD_ACTIVE_STATUS == giftActive.getActInd()) {
				result.setCode(ConstData.NOT_FOUND_CODE);
				throw new StewardException("0x000A06","该卡已激活");
			}
			//如果激活码与gift表数据不匹配
			if (!activeId.equals(giftActive.getActiveid()) || StringUtils.isEmpty(giftActive.getActiveid())) {
				result.setCode(ConstData.NOT_FOUND_CODE);
				throw new StewardException("0x000A05","激活码无效");
			}

			giftActive.setActInd(ConstData.CARD_ACTIVE_STATUS);
//			giftActive.setActType(ConstData.CARD_ACTIVE_TYPE_APP);
			mobGiftActiveMapper.updateByPrimaryKeySelective(giftActive);

			Customer customer = null;
			List<Customer> customers = customerMapper.selectCustomersByPhone(telephone);
			if (customers == null || customers.isEmpty()) {
				//创建customer
				customer = createCustomer(telephone);
			}else{
				boolean flag = true;//设置标志 是否当前customer有没有绑card数据
				for (Customer cust : customers) {
					if (cust.getCards() == null || cust.getCards().isEmpty()) {
						customer = cust;//将卡绑在当前的这个customer上
						flag = false;
						break;
					}
				}
				if (flag) {
					//创建customer
					customer = createCustomer(telephone);
				}
			}
			card.setCustId(customer.getId());
			cardMapper.updateByPrimaryKeySelective(card);//将custId更新到card上面
			CardTypeService cardTypeService = cardTypeServiceMapper.selectServiceInfoByCardTypeId(card.getCardtypeId());
			if (cardTypeService == null) {
				result.setCode(ConstData.NOT_FOUND_CODE);
				throw new StewardException("0x000A07","无法获取年卡附加服务的数据");
			}
			CardServicesRela cardServicesRela = createCardServicesRela(cardId, cardTypeService);
			ProductInfo productInfo = productInfoMapper.selectByPrimaryKey(cardTypeService.getProId());
			if (productInfo == null) {
				result.setCode(ConstData.NOT_FOUND_CODE);
				throw new StewardException("0x000A08","无法获取年卡对应的产品的数据");
			}
			Consume consume = createConsume(cardId, cardNO, customer.getId(), productInfo.getBidAmt());
			ConsumeDetail detail = createConsumeDetail(productInfo.getName(), productInfo.getId(), consume.getId(), productInfo.getBidAmt());
			result.setCode(ConstData.SUCCESS_CODE);
			result.setMessage("你的年卡已激活");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			result.setMessage(e.getMessage());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //抛异常 手动回滚
		}
		return result;
	}
	
	
	

	/**
	 *
	 * @param cardId
	 * @param cardTypeService
	 * @return
	 */
	private CardServicesRela createCardServicesRela(String cardId,CardTypeService cardTypeService){
		CardServicesRela cardServicesRela = new CardServicesRela();
		cardServicesRela.setAddDate(new Date());
		cardServicesRela.setCardId(cardId);
		cardServicesRela.setProId(cardTypeService.getProId());
		cardServicesRela.setIsFree(cardTypeService.getIsFree());
		cardServicesRela.setCntRate(cardTypeService.getCntRate());
		cardServicesRela.setConsumeCnt(cardTypeService.getConsumeCnt());
		cardServicesRela.setId(UUID.randomUUID().toString());
//		cardTypeServiceMapper.insert(cardTypeService);//插入数据
		cardServicesRelaMapper.insert(cardServicesRela);
		return cardServicesRela;
	}

	/**
	 *
	 * @param proName
	 * @param proId
	 * @param orderId
	 * @param amt
	 * @return
	 */
	private ConsumeDetail createConsumeDetail(String proName,String proId,String orderId,BigDecimal amt){
		ConsumeDetail consumeDetail = new ConsumeDetail();
		consumeDetail.setProName(proName);
		consumeDetail.setProId(proId);
		consumeDetail.setAddDate(new Date());
		consumeDetail.setOrderId(orderId);
		consumeDetail.setAccountDet(amt);
		consumeDetail.setId(UUID.randomUUID().toString());
		consumeDetailMapper.insert(consumeDetail);
		return consumeDetail;
	}

	/**
	 *
	 * @param cardId
	 * @param cardNO
	 * @param cusomerId
	 * @param amt
	 * @return
	 */
	private Consume createConsume(String cardId,String cardNO,String cusomerId,BigDecimal amt){
		Consume consume = new Consume();
		consume.setAddDate(new Date());
		consume.setCardId(cardId);
		consume.setCardNo(cardNO);
		consume.setCustId(cusomerId);
		consume.setStatusCd("1");
		consume.setSalesAmt(amt);
		consume.setOrderType(3);//办卡
		consume.setId(UUID.randomUUID().toString());
		consumeMapper.insert(consume);//保存
		return consume;
	}

	/**
	 *
	 * @param telephone
	 * @return
	 */
	private Customer createCustomer(String telephone){
		MobReg reg = mobRegMapper.queryMobRegInfoByPhone(telephone);
		Customer customer = new Customer();
		customer.setTelphone(telephone);
		customer.setAddDate(new Date());
		customer.setCustName(reg.getNickname());
		customer.setIsMember(true);
		customer.setId(UUID.randomUUID().toString());
		customerMapper.insert(customer);
		return customer;
	}

}
